﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using ProduceBasicData.Api.Application.Command.RBAC.Department;
using ProduceBasicData.Domain.RBAC;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.RBAC.Department
{
    /// <summary>
    /// 部门录入处理类
    /// </summary>
    public class CreateDepartmentHandler : IRequestHandler<CreateDepartmentCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<DepartmentModel> _departmentRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository"></param>
        /// <param name="mapper"></param>
        public CreateDepartmentHandler(IBaseRespository<DepartmentModel> departmentRepository, IMapper mapper)
        {
            _departmentRepository = departmentRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理部门录入请求
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CreateDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //将命令转换为领域模型
                var department = _mapper.Map<DepartmentModel>(request);
                //判断部门是否存在
                var departmentExist = await _departmentRepository.GetAll().AnyAsync(x => x.DepartmentName == department.DepartmentName);
                if (departmentExist != false)
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "部门已存在"
                    };
                }
                //保存类型
                var result = await _departmentRepository.AddAsync(department);
                if (result > 0)
                {
                    return new ApiResult<int>
                    {
                        Data = result,
                        Code = ApiEnum.Success,
                        Msg = "部门录入成功"
                    };
                }
                else
                {
                    return new ApiResult<int>
                    {
                        Code = ApiEnum.Failed,
                        Msg = "信息录入失败"
                    };
                }
            }
            catch (Exception ex)
            {
                return new ApiResult<int>
                {
                    Code = ApiEnum.Failed,
                    Msg = ex.Message
                };
            }
        }
    }
}
